import requests


class GiteeClient:
    def __init__(self, token):
        self.token = token

    def get_comments(self, owner, repo, issue_number):
        """获取 issue 的所有评论"""
        # https://gitee.com/api/v5/repos/src-openeuler/swtpm/issues/I5EXUA/comments?page=1&per_page=20&order=asc
        url = f"https://gitee.com/api/v5/repos/{owner}/{repo}/issues/{issue_number}/comments"
        resp = requests.get(
            url,
            params={
                "access_token": self.token,
                "order": "asc",
                "page": 1,
            },
        )
        return resp.json()

    def get_issues(self, owner, repo, q):
        """仓库的所有 issues"""
        url = f"https://gitee.com/api/v5/repos/{owner}/{repo}/issues"
        resp = requests.get(
            url,
            params={
                "access_token": self.token,
                "state": "all",
                "sort": "created",
                "direction": "desc",
                "page": 1,
                "per_page": 20,
                "q": q,
            },
        )
        return resp.json()


BOT_ID = 5329419


def get_user_comment(comments):
    ret = []
    for comment in comments:
        if comment["user"]["id"] != BOT_ID:
            ret.append(comment)
    return ret


if __name__ == "__main__":
    client = GiteeClient("f8b6a330dee3bd76f9fe36b8dcbd0a2c")
    res = client.get_issues("src-openeuler", "swtpm", "CVE-2020-28407")
    import json

    print(json.dumps(res, indent=4))

    comments = client.get_comments("src-openeuler", "swtpm", res[0]["number"])
    for comment in get_user_comment(comments):
        print(comment["body"])
    print(res[0]["html_url"])
